package org.example.service;

import javafx.collections.ObservableList;
import org.example.controller.JavaProcessManagementController;
import org.example.controller.Loading;
import org.example.model.ApplicationProcess;
import org.example.model.Plan;
import org.example.utils.CmdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.awt.geom.AreaOp;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author wwy
 * @date 2020-11-28 16:46
 */
@Service
public class CloseApplicationService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CloseApplicationService.class);
    @Autowired
    private StartApplicationService startApplicationService;
    @Autowired
    private JavaProcessManagementController javaProcessManagementController;
    @Autowired
    private ApplicationStatusService applicationStatus;
    private CmdUtils cmdUtils = new CmdUtils();

    /**
     * 关闭全部
     * @param loading
     * @return
     */
    public int closeAll(Loading loading){
        int successCount = 0;
        int errorCount = 0;
        Map<String, ObservableList<ApplicationProcess>> applicationDataMap = javaProcessManagementController.getApplicationDataMap();
        for (Map.Entry<String, ObservableList<ApplicationProcess>> stringObservableListEntry : applicationDataMap.entrySet()) {
            ObservableList<ApplicationProcess> applicationProcessObservableList = stringObservableListEntry.getValue();
            for (ApplicationProcess applicationProcess : applicationProcessObservableList) {
                int close = this.close(applicationProcess);
                if(close == 0){
                    //关闭成功
                    successCount ++;
                }
                if(close == 1){
                    //关闭失败
                    errorCount ++;
                }
                if(close == 2){

                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                loading.showMessage("关闭成功应用："+successCount+",启动失败应用："+errorCount);
            }
        }
        return 1;
    }
    public int close(ApplicationProcess applicationProcess){
        if(applicationProcess.getAppName().contains(".exe") || applicationProcess.getAppName().contains(".EXE")){
            //exe程序关闭
            return this.closeExe(applicationProcess);
        }else if(applicationProcess.getAppName().contains(".jar") || applicationProcess.getAppName().contains(".JAR")){
            //jar文件关闭
            return this.closeExe(applicationProcess);
        }else{
            //其他程序关闭
            return this.closeExe(applicationProcess);
        }
    }
    /**
     * 关闭exe软件
     * @param applicationProcess
     */
    public int closeExe(ApplicationProcess applicationProcess){
        boolean b;
        //软件是否启动
        if(applicationProcess.getAppName().contains(".jar") || applicationProcess.getAppName().contains(".JAR")){
            b = applicationStatus.applicationStatusByJar(applicationProcess.getAppName(),applicationProcess.getAppAddress());
        }else{
            b = applicationStatus.applicationStatus(applicationProcess.getAppName(),applicationProcess.getAppAddress());
        }

        if(b){
            //软件已启动可以关闭
            List<String> commend = new ArrayList<String>();
            commend.add("taskkill");
            commend.add("/pid");
            commend.add(applicationProcess.getPid());
            commend.add("-t");
            commend.add("-f");
            String outstring = null;
            try {
                ProcessBuilder builder = new ProcessBuilder();
                builder.command(commend);
                //将标准输入流和错误输入流合并，通过标准输入流程读取信息
                builder.redirectErrorStream(true);
                Process p = builder.start();
                outstring = cmdUtils.waitFor(p);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            if(outstring == null || outstring.equals("error")){
                LOGGER.info("关闭应用失败");


            }else{
                //String outStringTs = outstring.replace(" ", "");
                //System.out.println(outstring);
                return 0;

            }
        }
        return 1;
    }





}
